package com.example.demo.control;

import com.example.demo.entity.Info;
import com.example.demo.repository.InfoRepository;
import com.example.demo.utils.BackResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/info")
public class InfoController {
    @Autowired
    private InfoRepository infoRepository;
    /*
    * 获取分页用户
    * */
    @GetMapping("/queryInfo")
    public Object list(Integer page, Integer pageSize){
        if (pageSize==null||page==null) {
            page=0;
            pageSize=15;
        }
        List<Info> data = infoRepository.findAllInfo(page * pageSize, pageSize);
        int total=infoRepository.total();
        Map<String,Object> map =new HashMap<>();
        map.put("list",data);
        map.put("total",total);
        return  BackResult.success(map);
    }
    @PostMapping("/addInfo")
    public Object addInfo(Info info,String title){
        /*
         * 添加信息
         * */
        Info result=infoRepository.findByTitle(title,1);
        if (result!=null){
         return  BackResult.fail("用户已存在！");
        }
        info.set_live(1);
        Info data=infoRepository.save(info);
        if (data!=null){
            return   BackResult.success(data);
        }else {
            return  BackResult.fail("添加失败！");
        }
    }
    /*
     * 删除信息 删除Id
     * */
    @PostMapping("/deleteInfo")
    public Object deleteUser(Integer id){
        Info info=infoRepository.findBy_live(id,1);
        if (info==null){
            return  BackResult.fail("信息不存在!");
        }
        infoRepository.deleteById(id);
        return  BackResult.success("删除成功！");
    }
    /*
     * 删除信息 更新_live
     * */
    @PostMapping("/removeInfo")
    public Object removeUser(Integer id){
        Info data=infoRepository.findBy_live(id,1);
        if (data==null){
            return BackResult.fail("信息不存在!");
        }
        data.set_live(0);
        infoRepository.save(data);
        return  BackResult.success(data);
    }
    /*
    * 修改信息
    * */
    @PostMapping("/updateInfo")
    public Object updateInfo(Info info,Integer id){
        Info info1=infoRepository.findBy_live(id,1);
        if (info1==null){
            return  BackResult.fail("信息不存在!");
        }
        info.set_live(1);
        Info data=infoRepository.save(info);
        return  BackResult.success(data);
    }
}
